var mongojs = require('mongojs');
var db = mongojs('emonitor', ['mongodb://xiong:xiong@ds043262.mongolab.com:43262/emonitor', 'counts']);
var counts = {};
counts.execute = function () {

var mapper = function () {
    emit(Math.floor(this.timeline/60000), {unhappy:this.unhappy, happy:this.happy, surprise:this.surprise, num:1});
    
};
 
var reducer = function (name, values){
  var n = {unhappy : 0, happy : 0, surprise : 0};
  for ( var i=0; i<values.length; i++ ){
    if (values[i].unhappy > 0.35) {
        n.unhappy++
    };
    if (values[i].happy > 0.8) {
        n.happy++
    };
    if (values[i].unhappy > 0.5) {
        n.surprise++
    };
  }
  return n;
};

db.emotions.mapReduce(
    mapper,
    reducer,  {
        out: "counts"
    }
);
};
module.exports = counts;